#!/usr/bin/env bash

################################################################################
# Runs pytest on files that have been modified.
#
# Usage:
#     check/pytest-changed-files [BASE_REVISION] [--pytest-flags]
#
# This tool is not clever; it does not understand dependencies between all
# files. If "x.py" or "x_test.py" have been modified, it will include
# "x_test.py" in the arguments given to pytest. That's all it does.
#
# You can specify a base git revision to compare against (i.e. to use when
# determining whether or not a file is considered to have "changed"). For
# example, you can compare against 'origin/master' or 'HEAD~1'.
#
# If you don't specify a base revision, the following defaults will be tried, in
# order, until one exists:
#
#     1. upstream/master
#     2. origin/master
#     3. master
#
# If none exists, the script fails.
#
# You can pass flags such as "-v" into pytest by placing them after the
# comparison id.
################################################################################

# Get the working directory to the repo root.
cd "$( dirname "${BASH_SOURCE[0]}" )"
cd $(git rev-parse --show-toplevel)

# Figure out which branch to compare against.
rest=$@
if [ ! -z "$1" ] && [[ $1 != -* ]]; then
    if [ "$(git cat-file -t $1 2> /dev/null)" != "commit" ]; then
        echo -e "\e[31mNo revision '$1'.\e[0m" >&2
        exit 1
    fi
    rev=$1
    rest=${@:2}
elif [ "$(git cat-file -t upstream/master 2> /dev/null)" == "commit" ]; then
    rev=upstream/master
elif [ "$(git cat-file -t origin/master 2> /dev/null)" == "commit" ]; then
    rev=origin/master
elif [ "$(git cat-file -t master 2> /dev/null)" == "commit" ]; then
    rev=master
else
    echo -e "\e[31mNo default revision found to compare against. Argument #1 must be what to diff against (e.g. 'origin/master' or 'HEAD~1').\e[0m" >&2
    exit 1
fi
echo "Comparing against revision '${rev}'." >&2

# Get the _test version of changed python files.
changed=$(git diff --name-only ${rev} -- \
    | grep "\.py$" \
    | sed -e "s/\.py$/_test.py/" \
    | sed -e "s/_test_test\.py$/_test.py/" \
    | perl -ne 'chomp(); if (-e $_) {print "$_\n"}' \
    | uniq \
)
num_changed=$(echo -e "${changed}" | wc -w)

# Run it.
echo "Found ${num_changed} differing files with associated tests." >&2
if [ -z "${changed}" ]; then
    exit 0
fi
pytest ${rest} ${changed}
